﻿using System;
using Microsoft.Practices.ServiceLocation;
using PMngr.Data;
using PMngr.Infrastructure;

namespace PMngr.Main
{
    public partial class ChangePassword : BaseControl
    {
        public ChangePassword()
        {
            InitializeComponent();
        }       

        private void BtnOkClick(object sender, EventArgs e)
        {
            var oldPwd = txtOldPwd.Text;
            var newPwd = txtNewPwd.Text;
            var comformPwd = txt2Pwd.Text;

            if (String.IsNullOrWhiteSpace(oldPwd) || String.IsNullOrWhiteSpace(newPwd) ||
                String.IsNullOrWhiteSpace(comformPwd))
                return;

            if (newPwd != comformPwd)
            {
                LogTrace(Utilities.NoConsistency, MessageType.Exclamation);
                return;
            }

            if (oldPwd == newPwd)
            {
                LogTrace(Utilities.NoModified, MessageType.Exclamation);
                return;
            }
            // update the new password into the database
            var principal = System.Threading.Thread.CurrentPrincipal;
            var repositoryFactory = ServiceLocator.Current.GetInstance<IRepositoryFactory>();
            using (var repository = repositoryFactory.CreateRepository())
            {
                var user = repository.Single<User>(u => u.Name == principal.Identity.Name);

                var success = oldPwd.VerifyMD5(user.EncryptPwd);
                if (!success)
                {
                    LogTrace(Utilities.OldPasswordError, MessageType.Exclamation);
                    return;
                }

                user.EncryptPwd = txtNewPwd.Text.MD5Encrypt();

                repository.CommitChanges();
            }
            LogTrace(Utilities.PasswordUpdated);
        }       
    }
}
